/**
 *  @author yinghui.zhang 角色管理
 */

Ext.ns("cn.christ.web.action.dict.role");
var roleView = cn.christ.web.action.dict.role.RoleView;
roleView = function() {
	var store, grid, formPanel, win, userstore, usergrid, userwin, grantmoduleTree, grantformPanel, grantwin;
	
	var fields =["id","roleName","roleCode","remark"];
	var sm =  new Ext.grid.CheckboxSelectionModel({ singleSelect: true });
	return {
		init : function() {
			
			// ------------------------------------------------- store
			store = this.createStore();
			
			//查询条件
			store.on('beforeload', function() {
				if(queryRole){
					name=Ext.getCmp('pname').getValue();
				}else{
					name=undefined;
				}
				this.baseParams = {
					"name" : name
				};
			});
			
			// ------------------------------------------------- grid
			grid = this.createGrid();
			if(queryRole){
				grid.on('rowdblclick', function(g, r, e) {
					roleView.editInit();
				});
			}
			
			grid.on('render', function(grid) {  
			    var store = grid.getStore();  // Capture the Store.  
			    var view = grid.getView();    // Capture the GridView.  
			    grid.tip = new Ext.ToolTip({  
			        target: view.mainBody,    // The overall target element.  
			        //delegate: '.x-grid3-row', // Each grid row causes its own seperate show and hide.  
			        delegate: '.x-grid3-cell',
			        trackMouse: true,         // Moving within the row should not hide the tip.  
			        renderTo: document.body,  // Render immediately so that tip.body can be  
			        anchor: 'top',                           //  referenced prior to the first show.  
			        listeners: {              // Change content dynamically depending on which element  
			                                  //  triggered the show.  
			            beforeshow: function updateTipBody(tip) {  
			            	var rowIndex = view.findRowIndex(tip.triggerElement);  
	                        var cellIndex = view.findCellIndex(tip.triggerElement);  
			                var cellIndex = view.findCellIndex(tip.triggerElement);
			                if(cellIndex>2){
				                var cell = view.getCell(rowIndex, cellIndex);  
		                        tip.body.dom.innerHTML = cell.innerHTML;  
			                }else{
			                	return false;
			                }
			            }  
			        }  
			    });  
			}); 
			// ------------------------------------------------- viewport
			new Ext.Viewport({ 
			      layout : 'fit',
				  items : [grid]
			});
			
			this.queryResItem();
		},
		
		createStore : function() {
			return new FrameWorkStore({
			     url : '/role/list.action',
			     fields : fields
		    });
		},
		
		createUserstore : function() {
			return new Ext.data.Store( {
						proxy : new Ext.data.HttpProxy( { url :  cfg.cxt+'/role_roleUserList.do' }),
						reader : new Ext.data.JsonReader({
							totalProperty : 'results',
							root : 'list',
							idProperty:'id'
						}, ["id","username","personname"] ),
						listeners : { 
							loadexception : bangni.storeLoadError
						},
						paramNames : { start : 'pageuser.start',limit : 'pageuser.limit',sort : 'pageuser.sort',dir : 'pageuser.dir' }
					});
		},
		
		createGrid : function() {
			return new ExtGrid(
						{
						    store : store,
							sm : sm,
							columnLines:true,
							columns : [new Ext.grid.RowNumberer(),sm,
								  {
								    header:'授权',
								    dataIndex : 'id',
									renderer : function(v, c, r) {
										return '<a href="javascript:void(0);"  onclick="roleView.grant(\''+r.data.roleName+'\');"><img src="'+cfg.cxt+'/images/extjsicon/grant.gif"/></a>';
									},
									align:'center',
									width : 15
							     },{
									sortable : true,
									dataIndex : "roleName",
									header : "角色名称",
									width : 30
								 },{
									sortable : true,
									dataIndex : "roleCode",
									header : "角色代码",
									width : 25
								 },{
									sortable : true,
									dataIndex : "remark",
									header : "描述"
								 }
								 
								 ],
							tbar : roleView.createTbar(),
							bbar : {
								id : 'page',
								xtype : 'pageinfobar',
								pageSize : 20,
								store : store,
								pageMethod : roleView.queryResItem
							}
					});
		},
		
		createUsergrid : function(){
			return new ExtGrid(
						{
								store : userstore,
								sm : sm,
								columns : [new Ext.grid.RowNumberer(),sm,
									 {
										sortable : true,
										dataIndex : "username",
										header : "用户名"
									 },  
									 {
										sortable : true,
										dataIndex : "personname",
										header : "真实名"
									 },{
										dataIndex : "id",
										header : "操作",
										width : 65,
										align:'center',
										renderer : function(value) {
											return '<a href="javascript:void(0);" onclick="roleView.delRelation('+value+');">移除关联</a>';
										}
									}],
								bbar : {
									id : 'pageuser',
									xtype : 'pageinfobar',
									pageSize : 10,
									store : userstore,
									pageMethod : roleView.queryUserItem
								}
					});
		
		},
		
		createTbar : function() {
		    if(queryRole){
		    	tbarOpr.push('->');
				tbarOpr.push(
						new Ext.form.TextField( {
						id : 'pname',
						emptyText : '请输入人员名称',
						enableKeyEvents : true,
						listeners : {
							specialkey : function(field, e) {
								if (e.getKey() == Ext.EventObject.ENTER) {
									roleView.queryResItem();
								}
							}
						},
						width : 120
						})
						);
				tbarOpr.push({
					text : '查询',
					iconCls : 'previewIcon',
					handler : function() {
						roleView.queryResItem();
					}
				}, '-'
				, {
				text : '刷新',
					iconCls : 'arrow_refreshIcon',
					handler : function() {
						roleView.queryResItem();
					}
				} );
			}
		    return tbarOpr;
		},
		
		queryResItem : function(v) {
			if ( !v ){
			   v = Ext.getCmp('page').pageSize;
			}
			store.load({
				params : {
					"page.start" : 0,
					"page.limit" : v
				}
		    });
		},
		
		queryUserItem : function(v) {
			if(!v) v = Ext.getCmp('pageuser').pageSize;
			userstore.load( {
				params : {
					"pageuser.start" : 0,
					"pageuser.limit" : v
				}
			});
		},
		
		createUserWindow : function(){
			return new ExtWin({
					    width : 600,
						height : 330,
						items : usergrid
				 });
		},
		
		clearForm : function(pForm){
			var formItems = pForm.items['items'];
			for (i = 0; i < formItems.length; i++) {
				element = formItems[i];
				element.setValue('');
				element.reset(); // 避免出现红色波浪线
			};
		},
		
		addInit : function() {
			this.onAddOrEditInit('common');
			var flag = Ext.getCmp('windowmode').getValue();
			if (typeof (flag) != 'undefined') {
				formPanel.form.getEl().dom.reset();
			} else {
				this.clearForm(formPanel.getForm());
			}
			win.show();
			win.setTitle('<center>新增角色信息</center>');
			Ext.getCmp('windowmode').setValue('add');
		},
		
		editInit : function() {
			this.onAddOrEditInit('common');
			var record = grid.getSelectionModel().getSelected();
			if (Ext.isEmpty(record)) {
				Ext.Mytip.msg('提示', '请先选择要修改的记录!');
				return;
			}
			formPanel.getForm().loadRecord(record);
			win.show();
			win.setTitle('<center>修改角色信息</center>');
			Ext.getCmp('windowmode').setValue('edit');
		},
		
		onAddOrEditInit : function(type){
			switch(type) {
				case 'common' : {
				     if(!formPanel){
						 formPanel = roleForm.createFormPanel();
					 } 
					 if(!win){
					 	 win = roleForm.createWindow();
					 }
				 } break;
				 
				 case 'grant' : {
				 	 if(!grantmoduleTree){
				 	 	 grantmoduleTree = roleForm.createGrantModuleTree();
				 	     roleForm.setGrantModuleTreeClick();
				 	 }
				 	 if(!grantformPanel){
				 	 	grantformPanel =  roleForm.createGrantformPanel();
				 	 }
				 	 if(!grantwin){
				 	 	grantwin = roleForm.createGrantWin();
				 	 	roleForm.setGrantWinOnShow();
				 	 }
				 } break;
				  
				 case 'roleuser' : {
				 	 if(!userstore){
				 	 	userstore =  this.createUserstore();
				 	 }
				 	 if(!usergrid){
				 	 	usergrid =  this.createUsergrid();
				 	 }
				 	 if(!userwin){
				 	 	userwin = this.createUserWindow();
				 	 	userwin.on('show',function(){
				 	 	 	userstore.removeAll();
							roleView.queryUserItem();
						});
				 	 }
				 } break;
				 
				 default : {
				 	 Ext.Mytip.msg('提示', '初始化操作类型['+type+']不存在！');
				 }
			}
			
		},
		
		subForm : function(url) {
			 var mode = Ext.getCmp('windowmode').getValue();
			 formPanel.form.submit({
				url : cfg.cxt+url,
				waitTitle : '提示',
				method : 'POST',
				waitMsg : '正在处理数据,请稍候...',
				success : function(form, action) {
					var r = action.result.status;
					if (r == 200){
						win.hide();
						roleView.queryResItem();
						form.reset();
						if (mode == 'add')
						    Ext.Mytip.msg('提示', '新增成功！');
						else
						    Ext.Mytip.msg('提示', '修改成功！');
					} else {
						Ext.Mytip.msg('提示', action.result.info);
					}
				},
				failure : bangni.sumbitError
			});
		},
		
		deleteItem : function() {
		   var record = grid.getSelectionModel().getSelected();
	       if (Ext.isEmpty(record)) {
				Ext.Mytip.msg('提示', '请先选择要删除的记录!');
				return;
			}
			Ext.Msg
			   .confirm(
					'请确认',
					'<span style="color:red"><b>提示：</b>继续删除吗？</span>',
					function(btn, text) {
						if (btn == 'yes') {
							Ext.Ajax.request({
								url : cfg.cxt+'/role/del.action',
								success : function(response) {
									 var r = Ext.decode(response.responseText);
									 if (r.success){
									 	if(r.status == 200){
											 roleView.queryResItem();
											
										 } 
									 	 Ext.Mytip.msg('提示', r.info);
									 } else {
										bangni.ajaxError(response);
									 }
								},
								failure : bangni.ajaxError,
								params : {
									"id" : record.data.id
								}
							});
						}
					});
		},
		
		openShow : function(v,n){
			 this.onAddOrEditInit('roleuser');
			 userstore.on('beforeload', function() {
					this.baseParams = {
						"role.id" : v
					};
			  });
			 userwin.setTitle('角色['+n+']已分配用户');
			 userwin.show();
		 },
		 
		 delRelation : function(v){
			 Ext.Msg
				.confirm(
						'请确认',
						'<span style="color:red"><b>提示：</b>继续移除关联吗？</span>',
						function(btn, text) {
							if (btn == 'yes') {
								 Ext.Ajax.request({
										url : cfg.cxt+'/role_delRelation.do',
										success : function(response) {
											var rt = Ext.decode(response.responseText);
											if (rt.success){
												roleView.queryUserItem();
											    Ext.Mytip.msg('提示', '移除关联成功！');
											} else {
												bangni.ajaxError(response);
											}
										},
								        failure : bangni.ajaxError,
										params : {
											"role.id" : v
										}
									});
							}
						});
		 },
		 
		 grant : function(name){
		 	 this.onAddOrEditInit('grant');
			 grantwin.setTitle('<div style="text-align:center;">角色[ '+name+' ]授权</div>');
			 grantwin.show();
		},
		
		editOnePermission : function(e,y){
			    var node  = grantmoduleTree.getSelectionModel().getSelectedNode();
				var record = grid.getSelectionModel().getSelected();
			    var param = 'principalType=1&principalId='+record.id+'&moduleId='+node.attributes.id+'&permissionExt='+e+'&yes='+y;
		     	ajaxSyncCall( cfg.cxt+'/acl/addOrUpdatePermission.action',param);
		},
		
		editPermission : function (param,url) {
			var record = grid.getSelectionModel().getSelected();
			param = String.format(param, record.id)
	     	return ajaxSyncCall( url , param);
		}
	}
}();
Ext.onReady(roleView.init, roleView);